package com.raos.example.thread.service;

import com.raos.example.thread.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * 用户服务实现类
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2022/6/16 10:31
 */
@Slf4j
@Service
public class UserService {

    // 假定的容器
    private Set<UserEntity> set = new HashSet<>();
    private Random random = new Random();

    @Autowired
    private OtherService otherService;

    // 注册逻辑
    public UserEntity register() {
        long startTime = System.currentTimeMillis();
        UserEntity userEntity = new UserEntity();
        userEntity.setId(random.nextInt(Integer.MAX_VALUE));
        userEntity.setUsername("YF"+userEntity.getId());
        userEntity.setPassword("YF"+userEntity.getId());
        if (set.contains(userEntity)) {
            throw new RuntimeException("当前用户已存在");
        } else {
            set.add(userEntity);
        }
        final CountDownLatch countDownLatch = new CountDownLatch(2); // 2 表示下面代码将由两个异步操作执行
        Map<String, Object> data = new ConcurrentHashMap<>();
        try {
            // 添加积分
            otherService.addPoints(userEntity, countDownLatch, data);

            // 发送短信
            otherService.sendSms(userEntity, countDownLatch, data);

            countDownLatch.await(); // 等待所有线程结束
            log.info(data.toString());
        } catch (InterruptedException e) {
            log.error("添加积分和发送短信出现问题：", e);
            Thread.currentThread().interrupt();
        }
        log.info("执行时长=【{}】毫秒", System.currentTimeMillis() - startTime);
        return userEntity;
    }

    public Set<UserEntity> getAll() {
        return this.set;
    }

}
